Fix APIStatusError.code type to accept int values - #3591
Conversation
The API can return integer error codes, but the type was Optional[str]. Changed to Optional[Union[str, int]] to match runtime behavior. Fixes openai#3531
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 29337aebd0
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
| if is_dict(body): | ||
| self.code = cast(Any, construct_type(type_=Optional[str], value=body.get("code"))) | ||
| self.code = cast(Any, construct_type(type_=Optional[Union[str, int]], value=body.get("code"))) |
There was a problem hiding this comment.
Preserve integer codes under Pydantic v1
Because the project still supports pydantic>=1.9,<3, this path still stringifies integer error codes for Pydantic v1 users: construct_type() validates unions with Pydantic before falling back, and Pydantic v1 tries the str arm before int, so a body like {"code": 123} produces e.code == "123" even though the new public type says int is possible. This leaves integer-code handling broken in a supported dependency configuration; avoid the coercing union validation for this field or otherwise preserve raw int values.
Useful? React with 👍 / 👎.
|
Good catch from the Codex review. construct_type() with Pydantic v1 would still coerce integer error codes to strings since Pydantic v1 tries the str arm before int in a union. Fixed in 8362642 by bypassing construct_type for the code field entirely. Instead of routing through Pydantic union validation, we now read the raw value from the body dict and preserve it as-is when it is already a str or int: code_value = body.get("code") This ensures integer codes like 123 are preserved as integers regardless of which Pydantic version is installed. |
Fixes #3531
Summary
The
APIStatusError.codeattribute (inherited fromAPIError) is typed asOptional[str]but the OpenAI API can return integer error codes at runtime. This causes type-checking issues for users who try to handle error codes.Changes
In
src/openai/_exceptions.py:Unionto thetypingimportscode: Optional[str] = Nonetocode: Optional[Union[str, int]] = Noneconstruct_typecall inAPIError.__init__fromtype_=Optional[str]totype_=Optional[Union[str, int]]so the runtime type construction also accepts integer valuesThis ensures the type annotation accurately reflects the possible runtime values.